package zirao.paylib;

import java.util.Map;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build.VERSION;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

public class Pay {
	// private static String TAG = Pay.class.getSimpleName();
	public static PayCallBack payCallBack;
	private static Activity mContext;
	private static IWXAPI wxAPI;
	private static Pay mInstance;

	private Pay() {
	}

	public static synchronized Pay getInstance(Activity context) {
		if (mInstance == null) {
			mInstance = new Pay();
			payCallBack = null;
		}
		if (context != null) {
			mContext = context;
		}

		return mInstance;
	}

	/*
	 * 微信支付请求
	 * 
	 * @ request 微信请求参数
	 * 
	 * @ appId 微信id
	 */
	public void reqWXPay(PayReq request, PayCallBack callBack) {
		if (null == request || TextUtils.isEmpty(request.appId)) {
			showToast(mContext, "请求参数和微信id不能为空哦！");
			return;
		}

		if (null == callBack) {
			showToast(mContext, "回调不能为空哦！");
			return;
		}
		payCallBack = callBack;
		PayCache.getInstance().wxAppId = request.appId;
		wxAPI = WXAPIFactory.createWXAPI(mContext, (String)null);
		if (isWXAppInstalledAndSupported()) {
			try {
				wxAPI.registerApp(request.appId);
				wxAPI.sendReq(request);// 调起支付
				Log.i(PayUtil.WXPAY_LOG, "step 2：调起微信支付");
			} catch (Exception e) {
				Log.i(PayUtil.WXPAY_LOG, "step 2 Error: 无法注册微信 " + request.appId + ". Exception: " + e.getMessage());
				Toast.makeText(mContext, "Error: 无法注册微信 " + request.appId + ". Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();	
			}
		} else {
			Log.i(PayUtil.WXPAY_LOG, "step 2 Error :您尚未安装微信或者安装的微信版本不支持！");
			Toast.makeText(mContext, "您尚未安装微信或者安装的微信版本不支持！", Toast.LENGTH_SHORT).show();
		}
	}

	/*
	 * 支付宝支付请求
	 * 
	 * @ orderInfo 后台返回的签名数据
	 * 
	 * @ isRSA2 是否使用RSA2秘钥
	 */
	public void reqAliPay(String data, Boolean isShowLoading, PayCallBack callBack) {
		if (TextUtils.isEmpty(data) || null == isShowLoading) {
			showToast(mContext, "订单信息和是否RSA2不能为空！");
			return;
		}

		if (null == callBack) {
			showToast(mContext, "回调不能为空哦！");
			return;
		}

		payCallBack = callBack;
		new payTask().doTask(data, isShowLoading);
	}

	private class payTask extends AsyncTask<Object, Void, String> {

		@SuppressLint("NewApi")
		public void doTask(String data, Boolean isShowLoading) {
			if (GetAndroidSDKVersion() < 11)
				execute(data, isShowLoading);
			else
				executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, data, isShowLoading);
		}

		@Override
		protected String doInBackground(Object... params) {
			String data = params[0].toString();
			Boolean isShowLoading = (Boolean) params[1];
			PayTask alipay = new PayTask(mContext);
			Map<String, String> result = alipay.payV2(data, isShowLoading);

			AliPayResult payResult = new AliPayResult((Map<String, String>) result);
			String resultStatus = payResult.getResultStatus();
			String resultInfo = payResult.getResult();// 同步返回需要验证的信息
			String memo = payResult.getMemo();
			PayResult keResult = new PayResult();
			Log.d("Pay", "resultStatus:" + resultStatus + ",resultInfo:" + resultInfo + ",memo:" + memo);
			keResult.setErrorDetail(memo);
			keResult.setResultDetail(resultInfo);
			// 判断resultStatus
			if (TextUtils.equals(resultStatus, "9000")) {// 9000代表支付成功
				keResult.setResult(PayResult.RESULT_SUCCESS);
			} else if (TextUtils.equals(resultStatus, "8000")) {// 正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
				keResult.setResult(PayResult.RESULT_UNKNOWN);
				if (TextUtils.isEmpty(memo)) {
					keResult.setErrorDetail("订单正在处理中，无法获取成功确认信息");
				}
				if (TextUtils.isEmpty(resultInfo)) {
					keResult.setResultDetail("订单正在处理中，无法获取成功确认信息");
				}
			} else if (TextUtils.equals(resultStatus, "6001")) {// 用户中途取消
				keResult.setResult(PayResult.RESULT_CANCEL);
			} else {
				/*
				 * if (TextUtils.equals(resultStatus, "4000")// 订单支付失败 ||
				 * TextUtils.equals(resultStatus, "5000")// 重复请求 ||
				 * TextUtils.equals(resultStatus, "6002")// 网络连接出错 ||
				 * TextUtils.equals(resultStatus, "6004")// 网络连接出错 //其它 其它支付错误 )
				 */
				keResult.setResult(PayResult.RESULT_FAIL);
				if (TextUtils.equals(resultStatus, "4000")) {
					if (TextUtils.isEmpty(memo)) {
						keResult.setErrorDetail("订单支付失败");
					}
					if (TextUtils.isEmpty(resultInfo)) {
						keResult.setResultDetail("订单支付失败");
					}					
				} else {
					if (TextUtils.isEmpty(memo)) {
						keResult.setErrorDetail("网络连接出错");
					}
					if (TextUtils.isEmpty(resultInfo)) {
						keResult.setResultDetail("网络连接出错");
					}
				}

			}

			if (null != payCallBack) {
				payCallBack.done(keResult);
			} else {
				showToast(mContext, "回调不能为空哦！");
			}
			return null;
		}

	}

    public static boolean isWXAppInstalledAndSupported() {
        boolean isWXAppInstalledAndSupported = false;
        if(wxAPI != null) {
            isWXAppInstalledAndSupported = wxAPI.isWXAppInstalled() && wxAPI.isWXAppSupportAPI() && wxAPI.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        }

        return isWXAppInstalledAndSupported;
    }
	
	private static Toast mToast = null;

	public static void showToast(final Context context, final String msg, final int duration) {
		if (mToast == null) {
			mToast = Toast.makeText(context, msg, duration);
		} else {
			mToast.setText(msg);
		}
		mToast.show();
	}

	public static void showToast(final Context context, final String msg) {
		showToast(context, msg, Toast.LENGTH_SHORT);
	}

	public static int GetAndroidSDKVersion() {
		int sysVersion = VERSION.SDK_INT;
		return sysVersion;
	}
}
